#※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
# File Name: local_settings.sh
# Author: GID5564
# Description: 本地设置
# Created Time: 22/11/23-21:09:19
#※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
#! /usr/bin/env bash

function __git_clone_ready__(){
    #安装tmoe-zsh前准备
    git clone ${MYGIT}/omz '/root/.zinit/omz'
    git clone ${MYGIT}/powerlevel10k /root/.zinit/themes/_local/powerlevel10k
    git clone ${MYGIT}/zinit '/root/.zinit/bin'
    git clone ${MYGIT}/fzf-tab '/root/.zinit/plugins/_local---fzf-tab'
    git clone ${MYGIT}/fsyh '/root/.zinit/plugins/_local---fast-syntax-highlighting'
}

function install_tmoe_zsh(){
    if [[ $(command -v zsh-i) ]]; then
        tip "${YELLOW}提示: ${RESET}${BLUE}${RED}TMOE-ZSH${RESET}${BLUE} 软件包已存在，无需重复安装!${RESET}"
    else
        chmod +x ${FILE_ZSH}
        cp -f ${FILE_ZSH} ${FILE_ZSH%/*}/.zshrc_bk
        rm -f ${FILE_ZSH}
        
        __git_clone_ready__
        
        #bash -c "$(curl -LfsS 'https://gitee.com/gid5564/zsh/raw/master/zsh.sh')"
        source ${BIN_PATH}/tmoe_zsh.sh
        #重新写入ZSH
        tip "${BLUE}写入到ZSH配置文件: ${FILE_ZSH}${RESET}"
        write_to_zshrc
        write_ini ${FILE_CONFIG} "boot" "ZSH" "true"    
    fi
}


#安装editer: vim
function install_vim(){
    local vundle=${SYS_ROOT}/.vim/bundle/Vundle.vim
    #安装基础包:
    local pkgs="vim,vim-scripts,vim-doc,vim-gtk"
    install_dpkg_packages ${pkgs}
    
    msg "${BLUE} vim初始化…${RESET}"
    #配置.vimrc
    if [[ -s ${FILE_VIM} ]];then
        chmod +x ${FILE_VIM}
        cp -f ${FILE_VIM} ${FILE_VIM%/*}/.vimrc_bk
        rm -f ${FILE_VIM}
    fi
    #安装插件管理器
    if [[ ! -s ${vundle} ]];then
        git clone ${MYGIT}/Vundle.git ${vundle}
    fi

    [[ -s ${vundle} ]] && config_vim
    
    unset pkgs
    unset vundle
}

function config_vim(){
    cat > ${FILE_VIM} <<-'EOF'
"################配置VIM################
"关闭vi兼容模式
set nocompatible

"关闭文件类型侦测
filetype off

"设置运行跟初始化Vundle的路径
set rtp+=~/.vim/bundle/Vundle.vim
set runtimepath+=~/vim/


"♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥
call vundle#begin("~/.vim/plugins")
"插件
Plugin 'VundleVim/Vundle.vim'
"vim-airline配置:优化vim界面"

"缩进指示线(开关→:IndentLinesToggle)
Plugin 'indentLine.vim'

"可以使得用户在vim编辑器中方便地查看源代码文件结构，它可以在vim窗口中划出一部分来显示源代码的函数、类、结构体等信息，用户可以从taglist中选择并进入
Plugin 'taglist.vim'

"自动格式化工具，安装后运行:Autopep8就可以自动依照pep8的标准自动格式化代码。
Plugin 'tell-k/vim-autopep8'

"美化状态栏，可以显示当前的虚拟环境、Git分支、正在编辑的文件等信息。
Plugin 'Lokaltog/vim-powerline'

"自动缩进
Plugin 'vimjas/vim-python-pep8-indent'

"python语法检查
Plugin 'vim-syntastic/syntastic'

"配色方案
Plugin 'altercation/vim-colors-solarized'
"添加注释
Plugin 'tpope/vim-commentary'

"Plugin 'vim-airline/vim-airline-superman'

"中文帮助文档
"Plugin "vimcn/vimcdoc"

"方法、变量列表
"Plugin 'Majutsushi/Tagbar'


"在插入模式下，用来自动补全括号、引号等
"Plugin 'jiangmiao/auto-pairs'

Plugin 'The-NERD-Commenter' 

Plugin 'luochen1990/rainbow' 

"加载目录树插件
"Plugin 'The-NERD-tree'
"Plugin 'scrooloose/nerdtree-red'
Plugin 'scrooloose/nerdtree'
"生成一个当前文件的结构图，快速定位函数及变量
"Plugin 'majutsushi/tagbar'

Plugin 'tpope/vim-fugitive'
Plugin 'tpope/vim-surround'

call vundle#end()
"♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥

"打开文件类型检测功能，对应上面的filetype off
filetype plugin indent on

"♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥

"■Tagbar
let g:tagbar_width=35
let g:tagbar_autofocus=1
let g:tagbar_left = 1
nmap <C-b> :TagbarToggle<CR>


"■vim-airline配置:
" 使用powerline打过补丁的字体
let g:airline_powerline_fonts = 1
" 开启tabline
let g:airline#extensions#tabline#enabled = 1
" tabline中当前buffer两端的分隔字符
let g:airline#extensions#tabline#left_sep = ' '
" tabline中未激活buffer两端的分隔字符
let g:airline#extensions#tabline#left_alt_sep = ' '
" tabline中buffer显示编号
let g:airline#extensions#tabline#buffer_nr_show = 1
" 映射切换buffer的键位
nnoremap [b :bp<CR>
nnoremap ]b :bn<CR>
" 映射<leader>num到num buffer
map <leader>1 :b 1<CR>
map <leader>2 :b 2<CR>
map <leader>3 :b 3<CR>
map <leader>4 :b 4<CR>
map <leader>5 :b 5<CR>
map <leader>6 :b 6<CR>
map <leader>7 :b 7<CR>
map <leader>8 :b 8<CR>
map <leader>9 :b 9<CR>

"■ctags 配置:Ctrl-l快捷键显示程序中的各种tags，包括变量和函数等。
set tags=tags
set autochdir
map <C-l> :TlistToggle<CR>
"设定系统中ctags程序的位置
let Tlist_Ctags_Cmd = '/usr/bin/ctags'       
"窗口出现在右侧
let Tlist_Use_Right_Window=1
"不同时显示多个文件的tag，只显示当前文件的
let Tlist_Show_One_File=1
"如果taglist窗口是最后一个窗口，则退出vim
let Tlist_Exit_OnlyWindow=1
"如果你想在启动vim后，自动打开taglist窗口
let Tlist_Auto_Open=0
"如果你希望在选择了tag后自动关闭taglist窗口
let Tlist_Close_On_Select=1
"设置窗口宽，Tlist_WinHeight和Tlist_WinWidth可以设置taglist窗口的高度和宽度，Tlist_Use_Horiz_Window为1设置taglist窗口横向显示
let Tlist_WinWidt=20

"■NERDTree 配置:Ctrl-t快捷键显示当前目录树
map <C-t> :NERDTreeToggle<CR>
let NERDTreeWinSize=20
"设置忽略.pyc文件：
""let NERDTreeIgnore=['\~$', '\.pyc$', '\.swp$']
let NERDTreeIgnore=['~$','.swp$', '.pyc$', '.pyo$', '.obj$', '.o$', '.so$', '.egg$', '^.git$', '^.svn$', '^.hg$' ]

"■pep8配置:Ctrl-g依照pep8的标准自动格式化代码
autocmd FileType python noremap <buffer> <C-g> :call Autopep8()<CR>

"■The-NERD-Commenter配置
" 注释的时候自动加个空格, 强迫症必配 
let g:NERDSpaceDelims=1 
" mm智能判断加上/解开注释 
map mm c 

"■rainbow配置
let g:rainbow_active = 1

"■离开插入模式后自动关闭预览窗口"
autocmd InsertLeave * if pumvisible() == 0|pclose|endif 



"♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥



"设置历史记录步数"
set history=1000
"当文件在外部被修改时，自动更新该文件"
set autoread

"激活鼠标的使用"
set mouse=a
set selection=exclusive
set selectmode=mouse,key

"保存全局变量"
set viminfo+=!

"带有如下符号的单词不要被换行分割"
set iskeyword+=_,$,@,%,#,-

"通过使用: commands命令，告诉我们文件的哪一行被改变过"
set report=0

"被分割的窗口间显示空白，便于阅读"
set fillchars=vert:\ ,stl:\ ,stlnc:\

"""""""""""""""""""""""""""""""""
"""=>字体和颜色<="""
"""""""""""""""""""""""""""""""""
"自动开启语法高亮"
syntax enable

"设置字体"
"set guifont=dejaVu\ Sans\ MONO\ 10
set guifont=Courier_New:h10:cANSI

"设置颜色"
"colorscheme desert

"高亮显示当前行"
set cursorline
hi cursorline guibg=#00ff00
hi CursorColumn guibg=#00ff00

"高亮显示普通txt文件（需要txt.vim脚本）"
au BufRead,BufNewFile *  setfiletype txt

"""""""""""""""""""""""""""""""
"""=>代码折叠功能<="""
"""""""""""""""""""""""""""""""
"激活折叠功能"
set foldenable
"set nofen（这个是关闭折叠功能）"

"设置按照语法方式折叠（可简写set fdm=XX）"
"有6种折叠方法：
"manual   手工定义折叠"
"indent   更多的缩进表示更高级别的折叠"
"expr     用表达式来定义折叠"
"syntax   用语法高亮来定义折叠"
"diff     对没有更改的文本进行折叠"
"marker   对文中的标志进行折叠"
set foldmethod=manual
"set fdl=0（这个是不选用任何折叠方法）"

"设置折叠区域的宽度"
"如果不为0，则在屏幕左侧显示一个折叠标识列
"分别用“-”和“+”来表示打开和关闭的折叠
set foldcolumn=0

"设置折叠层数为3"
setlocal foldlevel=3

"设置为自动关闭折叠"
set foldclose=all

"用空格键来代替zo和zc快捷键实现开关折叠"
"zo O-pen a fold (打开折叠)
"zc C-lose a fold (关闭折叠)
"zf F-old creation (创建折叠)
"nnoremap <space> @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>

"""""""""""""""""""""""""""""""""""
"""=>文字处理<="""
"""""""""""""""""""""""""""""""""""
"使用空格来替换Tab"
set expandtab

"设置所有的Tab和缩进为4个空格"
set tabstop=4

"设定<<和>>命令移动时的宽度为4"
set shiftwidth=4

"使得按退格键时可以一次删除4个空格"
set softtabstop=4
set smarttab

"缩进，自动缩进（继承前一行的缩进）"
"set autoindent 命令打开自动缩进，是下面配置的缩写
"可使用autoindent命令的简写，即“:set ai”和“:set noai”
"还可以使用“:set ai sw=4”在一个命令中打开缩进并设置缩进级别
set ai
set cindent

"智能缩进"
set si

"自动换行”
set wrap

"设置软宽度"
set sw=4

"行内替换"
set gdefault

""""""""""""""""""""""""""""""""""
"""=>Vim 界面<="""
""""""""""""""""""""""""""""""""""
"增强模式中的命令行自动完成操作"
set wildmenu

"使vim支持256颜色
set t_Co=256

"显示标尺"
set ruler

"设置命令行的高度"
set cmdheight=1

"显示行数"
set nu

"不要图形按钮"
set go=

"在执行宏命令时，不进行显示重绘；在宏命令执行完成后，一次性重绘，以便提高性能"
set lz

"使回格键（backspace）正常处理indent, eol, start等"
set backspace=eol,start,indent

"允许空格键和光标键跨越行边界"
set whichwrap+=<,>,h,l

"设置魔术"
set magic

"关闭遇到错误时的声音提示"
"关闭错误信息响铃"
set noerrorbells

"关闭使用可视响铃代替呼叫"
set novisualbell

"高亮显示匹配的括号([{和}])"
set showmatch

"匹配括号高亮的时间（单位是十分之一秒）"
set mat=2

"光标移动到buffer的顶部和底部时保持3行距离"
set scrolloff=3

"搜索逐字符高亮"
set hlsearch
set incsearch

"搜索时不区分大小写"
"还可以使用简写（“:set ic”和“:set noic”）"
set ignorecase

"用浅色高亮显示当前行"
autocmd InsertLeave * se nocul
autocmd InsertEnter * se cul

"输入的命令显示出来，看的清楚"
set showcmd

"检测不必要的空格
"autocmd BufRead,BufNewFile *.py,*.pyw,*.c,*.h match BadWhiteSpace /\s\+$/


""""""""""""""""""""""""""""""""""""
"""=>编码设置<="""
""""""""""""""""""""""""""""""""""""
"设置编码"
set encoding=utf-8
set fencs=utf-8,ucs-bom,shift-jis,gb18030,gbk,gb2312,cp936

"设置文件编码"
set fileencodings=utf-8

"设置终端编码"
set termencoding=utf-8

"设置语言编码"
set langmenu=zh_CN.UTF-8
set helplang=cn

"""""""""""""""""""""""""""""
"""=>其他设置<="""
"""""""""""""""""""""""""""""
"开启新行时使用智能自动缩进"
set smartindent
set cin
set showmatch

"在处理未保存或只读文件的时候，弹出确认"
set confirm

"隐藏工具栏"
set guioptions-=T

"隐藏菜单栏"
set guioptions-=m

"置空错误铃声的终端代码"
set vb t_vb=

"显示状态栏（默认值为1，表示无法显示状态栏）"
set laststatus=2

"状态行显示的内容"
set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [POS=%l,%v][%p%%]\ %{strftime(\"%d/%m/%y\ -\ %H:%M:%S\")}

"粘贴不换行问题的解决方法"
set pastetoggle=<F9>

"设置背景颜色"
"set background=dark
if has('gui_running')
  set background=dark
  "colorscheme solarized
else
  "colorscheme Zenburn
  set background=light
endif

"文件类型自动检测，代码智能补全"
set completeopt=longest,preview,menu

"共享剪切板"
set clipboard+=unnamed

"从不备份"
set nobackup
set noswapfile

"自动保存"
set autowrite

"显示中文帮助"
if version >= 603
        set helplang=cn
        set encoding=utf-8
endif

"设置高亮相关项"
highlight Search ctermbg=black ctermfg=white guifg=white guibg=black

""""""""""""""""""""""""""""""""
"""=>在shell脚本开头自动增加解释器以及作者等版权信息<="""
""""""""""""""""""""""""""""""""
"新建.py,.c,.h,.sh,.java文件，自动插入文件头 
autocmd BufNewFile *.py,*.cpp,*.[ch],*.sh,*.java exec ":call SetTitle()" 
""定义函数SetTitle，自动插入文件头 
func SetTitle() 
	"如果文件类型为.sh文件 
		if &filetype == 'sh' 
		call setline(1, "#※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※") 
		call setline(2, "# File Name: ".expand("%")) 
		call setline(3, "# Author: GID5564") 
		call setline(4, "# Description:") 
		call setline(5, "# Created Time: ".strftime("%d/%m/%y-%H:%M:%S")) 
		call setline(6, "#※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※") 
        call setline(7, "#! /usr/bin/env bash")
		call setline(8, "")
elseif  &filetype == 'python'
		call setline(1,"#! /usr/bin/python3")
    	call setline(2,"# -*- coding: UTF-8 -*-")
        call setline(3,"  ")
        call setline(4, "\'\'\'※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※")
		call setline(5, "File Name: ".expand("%"))
		call setline(6, "Author: GID5564")
		call setline(7, "Description: ")
        call setline(8,"Version: 1.0")
		call setline(9, "Created Time: ".strftime("%d/%m/%y-%H:%M:%S"))
		call setline(10, "※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※\'\'\'")
       call setline(11,"") 
  else   
		call setline(1, "/* ※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※") 
		call setline(2, "	> File Name: ".expand("%")) 
		call setline(3, "	> Author: GID5564") 
		call setline(4, "	> Description: ") 
		call setline(5, "	> Created Time: ".strftime("%d/%m/%y-%H:%M:%S")) 
		call setline(6, " ※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※ */") 
		call setline(7, "")
	endif

"C++
	if &filetype == 'cpp'
		call setline(8,"#include<iostream>")
    	call setline(9, "using namespace std;")
		call setline(10, "")
	endif

"C
	if &filetype == 'c'
		call setline(8, "#include<stdio.h>")
		call setline(9, "")
	endif

"Java
	if &filetype == 'java'
		call setline(8,"public class ".expand("%:r"))
    	call setline(9,"")
	endif
"新建文件后，自动定位到文件末尾
autocmd BufNewFile * normal G
endfunc 

"按Ctrl-r直接在vim中执行代码
map <C-R> :call CompileRunGcc()<CR>
func! CompileRunGcc()
    exec "w"
    if &filetype == 'c'
        exec "!g++ % -o %<"
        exec "! ./%<"
    elseif &filetype == 'cpp'
        exec "!g++ % -o %<"
        exec "! ./%<"
    elseif &filetype == 'java' 
        exec "!javac %" 
        exec "!java %<"
    elseif &filetype == 'sh'
        :!./%
    elseif &filetype == 'python'
        exec "!time python %"
    endif
endfunc

"按Ctrl-d直接在vim中执行代码
map <C-d> :call Rungdb()<CR>
func! Rungdb()
    exec "w"
    if &filetype == 'cpp'
         exec "!g++ % -g -o %<"
         exec "!gdb ./%<"
    elseif &filetype == 'c'
         exec "!g++ % -g -o %<"
         exec "!gdb ./%<"
    elseif &filetype == 'python'
         exec "!time pytest %"
    endif
endfunc


"#######################################
EOF
# 更新vim配置
vim +PluginInstall +qall
}


function set_locales(){
    msg "${GREEN}设置中文支持: ${RESET}${YELLOW}zh_CN.UTF-8${RESET}"
    install_dpkg_package locales
    sudo dpkg-reconfigure locales
    echo "export LANG=zh_CN.UTF-8" >> ${FILE_BASH}
    echo "export LANG=zh_CN.UTF-8" >> ${FILE_ZSH}
    success "修改完成!"
}

function set_tzdata(){
    msg "${GREEN}设置本地时区: ${RESET}${YELLOW}ASIA/shanghai${RESET}"
    install_dpkg_package tzdata
    sudo dpkg-reconfigure tzdata
    success "修改完成!"
}

function edit_motd(){
    #编辑问候会话motd
    tip "${GREEN}打开文件后，按[${RESET}${RED}i${RESET}${GREEN}]编辑，编辑完后，先按${RED}[ESC]${RESET}${GREEN}键，再输入${RESET}${RED}:wq${RESET}${GREEN} 保存即可。${RESET}"
    #备份
    chmod +x ${FILE_MOTD}
    cp -f ${FILE_MOTD} ${FILE_MOTD%/*}/.motd_bk
    vim ${FILE_MOTD}

    success "修改完毕!"
    warn "会话需要${RESET}${RB_RED}重启AidLux${RESET}${WARN}才能生效!${RESET}"
}

function edit_boot(){
    #.rc.local
    notice "${GREEN}打开文件后，按[${RESET}${RED}i${RESET}${GREEN}]编辑，编辑完后，先按${RED}[ESC]${RESET}${GREEN}键，再输入${RESET}${RED}:wq${RESET}${GREEN} 保存即可。${RESET}"
    chmod +x ${FILE_RC}
    cp -f ${FILE_RC} ${FILE_RC%/*}/.rc.local_bk
    vim ${FILE_RC}
    success "修改完毕!"
    warn "会话需要${RESET}${RB_RED}重启AidLux${RESET}${WARN}才能生效!${RESET}"
}

#设置软连接
function create_link(){
    #引用目录路径
    local true_path
    #链接目录路径
    local link_path
    #目录名称
    local dir_name
    
    Msg "请输入指向目录路径: "
    read true_path
    Msg "请输入链接目录路径: "
    read link_path    
    Msg "请输入链接目录名称: "
    read dir_name
    
    
    create_link_to_sdcard ${true_path} ${link_path} ${dir_name}
    
    if [[ ${link_path:${#link_path[@]}-1:1} = '/' ]];then
        link_path=${link_path}${dir_name}
    else
        link_path=${link_path}/${dir_name}
    fi
    #写入ini
    write_ini ${FILE_CONFIG} "link" ${link_path} ${true_path}
}


#配置当前SHELL
function EditShellConfig(){
    local sh_cmd
    
    #sh_cmd=${SHELL##*/}
    sh_cmd=${CURRENT_SHELL}
    msg "${BLUE}检测到你的当前Shell为${RESET}${YELLOW}${sh_cmd}${RESET}"
		#不区分大小写判断
		case ${sh_cmd} in
		*bash*)
			msg "${BLUE}将使用${RESET}${YELLOW}vim${RESET}${BLUE}编辑${RESET}${YELLOW}.bashrc${RESET}${BLUE}文件，修改完成请按${RESET}${RED}ESC+:wq${RESET}${BLUE}退出。${RESET}"
			press 
			vim ${FILE_BASH}
			;;
        *zsh*)
            msg "${BLUE}将使用${RESET}${YELLOW}vim${RESET}${BLUE}编辑${RESET}${YELLOW}.zshrc${RESET}${BLUE}文件，修改完成请按${RESET}${RED}ESC+:wq${RESET}${BLUE}退出。${RESET}"
			press 
			vim ${FILE_ZSH}
			;;
		*fish*)
			msg "${BLUE}将使用${RESET}${YELLOW}vim${RESET}${BLUE}编辑${RESET}${YELLOW}.fishrc${RESET}${BLUE}文件，修改完成请按${RESET}${RED}ESC+:wq${RESET}${BLUE}退出。${RESET}"
			press 
			
			mkdir ${SYS_ROOT}/.config/fish
			vim ${SYS_ROOT}/.config/fish/config.fish
			;;
		*)
			Msg "${BLUE}未知的Shell类型，请手动输入你的Shell的初始化文件位置：${RESET}" 
			read -n rc
			msg "${BLUE}将使用${RESET}${YELLOW}vim${RESET}${BLUE}编辑${RESET}${YELLOW}${rc}${RESET}${BLUE}文件，修改完成请按${RESET}${RED}ESC+:wq${RESET}${BLUE}退出。${RESET}"
			press 
			
			vim $rc
			;;
		esac
}


function configuration_file(){
    local file=$1
    msg "${GREEN}配置: ${RESET}${YELLOW}${file}${RESET}"
    tip "${GREEN}打开文件后，按[${RESET}${RED}i${RESET}${GREEN}]编辑，编辑完后，先按${RED}[ESC]${RESET}${GREEN}键，再输入${RESET}${RED}:wq${RESET}${GREEN} 保存即可。${RESET}"
    vim ${file}
    success "${GREEN}修改完成!${RESET}"
}


















